package io.renren.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.renren.annotation.Login;
import io.renren.annotation.LoginUser;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageInfo;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.entity.ParkExamineEntity;
import io.renren.entity.SysUserEntity;
import io.renren.entity.TokenEntity;
import io.renren.entity.UserEntity;
import io.renren.service.ParkExamineService;
import io.renren.service.SysUserService;
import io.renren.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.UUID;


/**
 * 停车场调查表
 *
 * @author hacken
 * @email hacken_hu@foxmail.com
 * @date 2021-01-27 21:25:27
 */
@RestController
@RequestMapping("parking/parkexamine")
@Api(tags = "停车场调查接口")
public class ParkExamineController {
    @Autowired
    private ParkExamineService parkExamineService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private MinioClient minioClient;
    @Value("${minio.bucketName}")
    private String bucketName;

    /**
     * 列表
     */
    @Login
    @RequestMapping("/list")
    @ApiOperation(value = "获取列表", response = ParkExamineEntity.class)
    public PageInfo list(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        String token = request.getHeader("token");
        //查询token信息
        TokenEntity tokenEntity = tokenService.queryByToken(token);
        //获取用户信息
        SysUserEntity user = userService.getById(tokenEntity.getUserId());
        IPage<ParkExamineEntity> page = parkExamineService.queryPage(params, user);
        PageInfo pageInfo = new PageInfo();
        pageInfo.setTotal((int) page.getTotal());
        pageInfo.setRows(page.getRecords());
        return pageInfo;
    }


    /**
     * 信息
     */
    @Login
    @RequestMapping("/info/{id}")
    public R info(@LoginUser @PathVariable("id") Long id) {
        ParkExamineEntity parkExamine = parkExamineService.getById(id);

        return R.ok().put("obj", parkExamine);
    }

    /**
     * 保存
     */
    @Login
    @RequestMapping("/save")
    public R save(@RequestBody ParkExamineEntity parkExamine, HttpServletRequest request) {
        String token = request.getHeader("token");
        //查询token信息
        TokenEntity tokenEntity = tokenService.queryByToken(token);
        //获取用户信息
        SysUserEntity user = userService.getById(tokenEntity.getUserId());
        parkExamine.setCreateTime(new Date());
        parkExamine.setCreateUserId(user.getUserId());
        parkExamine.setCreateUser(user.getUsername());
        parkExamine.setDeptId(user.getDeptId());

        ParkExamineEntity parkExamineObj = parkExamineService.getOne(new QueryWrapper<ParkExamineEntity>().eq("park_name",parkExamine.getParkName()));
        if(parkExamineObj != null){
            return R.error(500,"该停车场已经存在，请勿重复提交");
        }
        parkExamineService.save(parkExamine);

        return R.ok();
    }

    /**
     * 修改
     */
    @Login
    @RequestMapping("/update")
    public R update(@RequestBody ParkExamineEntity parkExamine) {
        ValidatorUtils.validateEntity(parkExamine);
        ParkExamineEntity parkExamineObj = parkExamineService.getOne(new QueryWrapper<ParkExamineEntity>().eq("park_name",parkExamine.getParkName()));
        if(parkExamineObj != null && !parkExamineObj.getId().equals(parkExamine.getId())){
            return R.error(500,"该停车场已经存在，请勿重复提交");
        }
        parkExamineService.updateById(parkExamine);

        return R.ok();
    }

    /**
     * 删除
     */
    @Login
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        parkExamineService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    @Login
    @RequestMapping("/updateImg")
    public R updateImg(@LoginUser @RequestParam Map<String, Object> params, @RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString().replaceAll("-", "")
                + fileName.substring(fileName.lastIndexOf("."));
        InputStream inputStream = null;
        String url = "";
        try {
            inputStream = file.getInputStream();
            PutObjectOptions options = new PutObjectOptions(inputStream.available(), -1);
            minioClient.putObject(bucketName, newName, inputStream, options);
            inputStream.close();
            url = minioClient.getObjectUrl(bucketName, newName);
        } catch (Exception e) {
            new RRException("数据保存异常");
        }
        return R.ok().put("url", url);
    }

}
